#include "preview.h"
#include "ui_preview.h"
#include<QSettings>
Preview::Preview(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::Preview)
{
    m_ui->setupUi(this);
    connect(m_ui->titlesList, SIGNAL(itemDoubleClicked(QListWidgetItem*)),
    this, SLOT(itemActivated(QListWidgetItem*)));

    connect(&http, SIGNAL(readyRead(const QHttpResponseHeader &)),
      this, SLOT(readData(const QHttpResponseHeader &)));

    connect(&http, SIGNAL(requestFinished(int, bool)),
      this, SLOT(finished(int, bool)));
}

Preview::~Preview()
{
    delete m_ui;
}

void Preview::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Preview::readData(const QHttpResponseHeader &resp)
 {
     if (resp.statusCode() != 200)
         http.abort();
     else {
         xml.addData(http.readAll());
         parseXml();
     }
 }

 void Preview::finished(int id, bool error)
 {
     if (error) {
         qWarning("Received error during HTTP fetch.");
         qWarning(http.errorString().toStdString().c_str());
     }
     else if (id == connectionId) {
        if(!feeds.isEmpty())
        {
            xml.clear();
            fetch(feeds.front());
            feeds.pop_front();
        }
     }
 }

void Preview::parseXml()
{
    while (!xml.atEnd()) {
     xml.readNext();
     if (xml.isStartElement()) {
         if (xml.name() == "item")
             linkString = xml.attributes().value("rss:about").toString();
         currentTag = xml.name().toString();
     } else if (xml.isEndElement()) {
         if (xml.name() == "item") {

             QListWidgetItem *item = new QListWidgetItem;
             item->setText(titleString);
             item->setData(1,linkString);
             m_ui->titlesList->addItem(item);
             titleString.clear();
             linkString.clear();
             desctiptionString.clear();
         }

     } else if (xml.isCharacters() && !xml.isWhitespace()) {
         if (currentTag == "title")
             titleString += xml.text().toString();
         else if (currentTag == "link")
             linkString += xml.text().toString();
         else if (currentTag == "description")
             desctiptionString += xml.text().toString();
     }
    }
    if (xml.error() && xml.error() != QXmlStreamReader::PrematureEndOfDocumentError) {
     qWarning(xml.errorString().toStdString().c_str());
     http.abort();
    }
}

 void Preview::itemActivated(QListWidgetItem * item)
 {
     qDebug(item->data(1).toString().toStdString().c_str());
     QDesktopServices::openUrl(QUrl(item->data(1).toString()));
 }

 void Preview::fetch(QString UrlAddr = QString())
 {
     xml.clear();
     QUrl url(UrlAddr);
     qDebug(UrlAddr.toStdString().c_str());
     http.setHost(url.host());
     connectionId = http.get(url.path());
 }

void Preview::on_refreshButton_clicked()
{
    m_ui->titlesList->clear();
    QSettings set("settings.ini",QSettings::IniFormat);
    set.beginGroup("feeds");
    QStringList URLs = set.allKeys();
    foreach(QString URL, URLs)
    {
        feeds<<set.value(URL).toString();
        qDebug(set.value(URL).toString().toStdString().c_str());
    }
    set.endGroup();
    if(!feeds.isEmpty())
    {
        fetch(feeds.front());
        feeds.pop_front();
    }
    fetch("http://company.yandex.ru/news/news.rss");
}

void Preview::on_titlesList_itemDoubleClicked(QListWidgetItem* item)
{
    itemActivated(item);
}
